package com.cjh.wxdemoserver.base.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cjh.wxdemoserver.base.entity.BaseEntity;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author ChenJH
 * @description 基础字段自动填充
 */

public class BaseDBFieldHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if(ObjectUtils.isNotEmpty(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            if (ObjectUtils.isEmpty(baseEntity.getCreateTime())) {
                baseEntity.setCreateTime(LocalDateTime.now());
            }
            if (ObjectUtils.isEmpty(baseEntity.getUpdateTime())) {
                baseEntity.setUpdateTime(LocalDateTime.now());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(ObjectUtils.isNotEmpty(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            if (ObjectUtils.isEmpty(baseEntity.getUpdateTime())) {
                baseEntity.setUpdateTime(LocalDateTime.now());
            }
        }
    }
}
